/**
 * 邮件通知服务
 * 支持从系统配置表读取模板和配置，集成163邮箱SMTP服务
 */

const nodemailer = require('nodemailer');
const { query } = require('../config/db');

/**
 * 从系统配置表获取配置
 * @param {string} configKey - 配置键
 * @returns {Promise<string>} 配置值
 */
async function getConfig(configKey) {
  try {
    const result = await query(
      'SELECT config_value FROM system_configs WHERE config_key = ?',
      [configKey]
    );
    
    if (result && result.length > 0) {
      return result[0].config_value;
    }
    
    return null;
  } catch (error) {
    console.error(`获取配置 ${configKey} 失败:`, error);
    return null;
  }
}

/**
 * 验证邮箱地址格式
 * @param {string} email - 邮箱地址
 * @returns {boolean} 是否有效
 */
function validateEmail(email) {
  if (!email || typeof email !== 'string') {
    return false;
  }
  
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email.trim());
}

/**
 * 渲染邮件模板
 * @param {string} template - 模板字符串
 * @param {Object} variables - 变量对象
 * @returns {string} 渲染后的内容
 */
function renderTemplate(template, variables) {
  if (!template || typeof template !== 'string') {
    return '';
  }

  let rendered = template;
  
  // 替换模板变量
  Object.keys(variables).forEach(key => {
    const placeholder = `{${key}}`;
    const value = variables[key] || '';
    rendered = rendered.replace(new RegExp(placeholder.replace(/[{}]/g, '\\$&'), 'g'), value);
  });

  return rendered;
}

/**
 * 格式化时间
 * @param {string|Date} dateTime - 时间
 * @returns {string} 格式化后的时间字符串
 */
function formatTime(dateTime) {
  if (!dateTime) return '';
  
  try {
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    });
  } catch (error) {
    console.error('时间格式化错误:', error);
    return dateTime.toString();
  }
}

/**
 * 发送订单通知邮件给停车场管理员
 * @param {string} managerEmail - 管理员邮箱地址
 * @param {Object} orderDetails - 订单详情
 * @returns {Promise<Object>} 发送结果
 */
async function sendOrderNotificationToManager(managerEmail, orderDetails) {
  try {
    console.log(`开始发送订单通知邮件 - 订单号: ${orderDetails.order_number}, 收件人: ${managerEmail}`);

    // 验证必要参数
    if (!managerEmail) {
      console.log('邮件发送跳过: 管理员邮箱地址为空');
      return {
        success: false,
        message: '管理员邮箱地址不能为空',
        skip: true
      };
    }

    if (!orderDetails.order_number) {
      console.log('邮件发送跳过: 订单号为空');
      return {
        success: false,
        message: '订单号不能为空',
        skip: true
      };
    }

    // 验证邮箱格式
    if (!validateEmail(managerEmail)) {
      console.log(`邮件发送跳过: 邮箱格式无效 ${managerEmail}`);
      return {
        success: false,
        message: '邮箱格式无效',
        skip: true
      };
    }

    // 检查邮件功能是否启用
    const emailEnabled = await getConfig('email_enabled');
    if (emailEnabled !== 'true') {
      console.log('邮件发送跳过: 邮件功能未启用');
      return {
        success: false,
        message: '邮件功能未启用',
        skip: true
      };
    }

    // 获取邮件模板
    const template = await getConfig('email_order_template');
    if (!template) {
      console.log('邮件发送跳过: 未找到订单邮件模板');
      return {
        success: false,
        message: '未找到订单邮件模板',
        skip: true
      };
    }

    // 构建模板变量
    const variables = {
      '订单号': orderDetails.order_number,
      '车牌号': orderDetails.license_plate || '',
      '停车场名称': orderDetails.parking_lot_name || '',
      '用户昵称': orderDetails.user_nickname || '',
      '用户手机': orderDetails.user_phone || '',
      '开始时间': formatTime(orderDetails.planned_start_time),
      '结束时间': formatTime(orderDetails.planned_end_time),
      '费用': orderDetails.final_amount || 0,
      '创建时间': formatTime(orderDetails.created_at || new Date())
    };

    // 渲染邮件内容
    const emailContent = renderTemplate(template, variables);
    
    // 获取SMTP配置
    const smtpConfig = await getConfig('email_smtp_config');
    if (!smtpConfig) {
      console.log('邮件发送跳过: 未找到SMTP配置');
      return {
        success: false,
        message: '未找到SMTP配置',
        skip: true
      };
    }

    let config;
    try {
      config = JSON.parse(smtpConfig);
    } catch (error) {
      console.log('邮件发送跳过: SMTP配置格式错误');
      return {
        success: false,
        message: 'SMTP配置格式错误',
        skip: true
      };
    }

    // 验证SMTP配置完整性
    if (!config.host || !config.port || !config.user || !config.pass) {
      console.log('邮件发送: SMTP配置不完整，使用模拟模式');
      
      // 模拟发送
      console.log('=== 邮件通知发送（模拟）===');
      console.log(`收件人: ${managerEmail}`);
      console.log(`主题: 新订单通知 - ${orderDetails.order_number}`);
      console.log(`内容: ${emailContent}`);
      console.log(`发送时间: ${new Date().toLocaleString('zh-CN')}`);
      console.log('============================');

      await new Promise(resolve => setTimeout(resolve, 100));

      return {
        success: true,
        message: '邮件发送成功（模拟）',
        data: {
          email: managerEmail,
          subject: `新订单通知 - ${orderDetails.order_number}`,
          content: emailContent,
          send_time: new Date().toISOString(),
          message_id: `mock_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
        }
      };
    }

    // 发送真实邮件
    return await sendEmail(managerEmail, `新订单通知 - ${orderDetails.order_number}`, emailContent, config);

  } catch (error) {
    console.error('邮件发送失败:', error);
    return {
      success: false,
      message: error.message || '邮件发送失败',
      error: error
    };
  }
}

/**
 * 使用SMTP发送邮件
 * @param {string} to - 收件人邮箱
 * @param {string} subject - 邮件主题
 * @param {string} content - 邮件内容
 * @param {Object} config - SMTP配置
 * @returns {Promise<Object>} 发送结果
 */
async function sendEmail(to, subject, content, config) {
  try {
    // 创建邮件传输器
    const transporter = nodemailer.createTransport({
      host: config.host,
      port: parseInt(config.port),
      secure: config.port == 465, // 465端口使用SSL，587端口使用STARTTLS
      auth: {
        user: config.user,
        pass: config.pass
      }
    });

    // 邮件选项
    const mailOptions = {
      from: `"省米停车系统" <${config.user}>`,
      to: to,
      subject: subject,
      text: content,
      html: content.replace(/\n/g, '<br>')
    };

    // 发送邮件
    const info = await transporter.sendMail(mailOptions);

    console.log('邮件发送成功:', info.messageId);

    return {
      success: true,
      message: '邮件发送成功',
      data: {
        messageId: info.messageId,
        response: info.response,
        envelope: info.envelope
      }
    };

  } catch (error) {
    console.error('SMTP邮件发送失败:', error);
    return {
      success: false,
      message: error.message || 'SMTP邮件发送失败',
      error: error
    };
  }
}

/**
 * 测试邮件发送功能
 * @param {string} testEmail - 测试邮箱地址
 * @returns {Promise<Object>} 测试结果
 */
async function testEmailSending(testEmail) {
  try {
    if (!validateEmail(testEmail)) {
      return {
        success: false,
        message: '测试邮箱格式无效'
      };
    }

    const testOrderDetails = {
      order_number: 'TEST' + Date.now(),
      license_plate: '测A12345',
      parking_lot_name: '测试停车场',
      user_nickname: '测试用户',
      user_phone: '13800138000',
      planned_start_time: new Date(),
      planned_end_time: new Date(Date.now() + 2 * 60 * 60 * 1000), // 2小时后
      final_amount: 10.00,
      created_at: new Date()
    };

    return await sendOrderNotificationToManager(testEmail, testOrderDetails);

  } catch (error) {
    console.error('测试邮件发送失败:', error);
    return {
      success: false,
      message: error.message || '测试邮件发送失败',
      error: error
    };
  }
}

module.exports = {
  sendOrderNotificationToManager,
  testEmailSending,
  validateEmail,
  renderTemplate,
  formatTime
};
